<template>
  <div class="main-layout" :class="{ 'sidebar-collapsed': sidebarCollapsed }">
    <!-- 顶部导航栏 -->
    <header class="main-header">
      <div class="header-left">
        <!-- Logo -->
        <div class="logo" @click="goHome">
          <img src="@/assets/images/logo.png" alt="Logo" class="logo-image" />
          <span class="logo-text">在线学习平台</span>
        </div>
        
        <!-- 导航菜单 -->
        <nav class="main-nav">
          <el-menu
            :default-active="activeMenu"
            mode="horizontal"
            class="nav-menu"
            @select="handleMenuSelect"
          >
            <el-menu-item index="/">
              <el-icon><House /></el-icon>
              <span>首页</span>
            </el-menu-item>
            
            <el-sub-menu index="courses">
              <template #title>
                <el-icon><Reading /></el-icon>
                <span>课程中心</span>
              </template>
              <el-menu-item index="/courses">全部课程</el-menu-item>
              <el-menu-item index="/courses/my">我的课程</el-menu-item>
              <el-menu-item index="/courses/favorite">收藏课程</el-menu-item>
            </el-sub-menu>
            
            <el-sub-menu index="exams">
              <template #title>
                <el-icon><Document /></el-icon>
                <span>考试中心</span>
              </template>
              <el-menu-item index="/exams">全部考试</el-menu-item>
              <el-menu-item index="/exams/my">我的考试</el-menu-item>
              <el-menu-item index="/exams/results">考试成绩</el-menu-item>
            </el-sub-menu>
            
            <el-menu-item index="/community">
              <el-icon><ChatDotRound /></el-icon>
              <span>学习社区</span>
            </el-menu-item>
          </el-menu>
        </nav>
      </div>
      
      <div class="header-right">
        <!-- 搜索框 -->
        <div class="search-box">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索课程、考试..."
            class="search-input"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        
        <!-- 通知 -->
        <el-dropdown trigger="click" @command="handleNotificationCommand">
          <div class="notification-btn">
            <el-badge :value="unreadCount" :hidden="unreadCount === 0">
              <el-icon><Bell /></el-icon>
            </el-badge>
          </div>
          <template #dropdown>
            <el-dropdown-menu class="notification-dropdown">
              <div class="notification-header">
                <span>通知消息</span>
                <el-button
                  text
                  size="small"
                  @click="markAllAsRead"
                  :disabled="unreadCount === 0"
                >
                  全部已读
                </el-button>
              </div>
              
              <div class="notification-list">
                <div
                  v-for="notification in notifications"
                  :key="notification.id"
                  class="notification-item"
                  :class="{ unread: !notification.read }"
                  @click="handleNotificationClick(notification)"
                >
                  <div class="notification-icon" :class="notification.type">
                    <el-icon v-if="notification.type === 'course'"><Reading /></el-icon>
                    <el-icon v-else-if="notification.type === 'exam'"><Document /></el-icon>
                    <el-icon v-else-if="notification.type === 'system'"><Bell /></el-icon>
                    <el-icon v-else><Message /></el-icon>
                  </div>
                  
                  <div class="notification-content">
                    <div class="notification-title">{{ notification.title }}</div>
                    <div class="notification-desc">{{ notification.description }}</div>
                    <div class="notification-time">{{ formatTime(notification.createdAt) }}</div>
                  </div>
                  
                  <div v-if="!notification.read" class="unread-dot"></div>
                </div>
              </div>
              
              <div class="notification-footer">
                <el-button text @click="viewAllNotifications">查看全部</el-button>
              </div>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        
        <!-- 主题切换 -->
        <el-tooltip content="切换主题" placement="bottom">
          <el-button
            class="theme-toggle"
            circle
            @click="toggleTheme"
          >
            <el-icon v-if="isDark"><Sunny /></el-icon>
            <el-icon v-else><Moon /></el-icon>
          </el-button>
        </el-tooltip>
        
        <!-- 用户菜单 -->
        <el-dropdown trigger="click" @command="handleUserCommand">
          <div class="user-menu">
            <el-avatar
              :size="36"
              :src="userInfo.avatar"
              class="user-avatar"
            >
              <el-icon><User /></el-icon>
            </el-avatar>
            <span class="username">{{ userInfo.nickname || userInfo.username }}</span>
            <el-icon class="dropdown-icon"><ArrowDown /></el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">
                <el-icon><User /></el-icon>
                个人中心
              </el-dropdown-item>
              <el-dropdown-item command="settings">
                <el-icon><Setting /></el-icon>
                账户设置
              </el-dropdown-item>
              <el-dropdown-item command="help">
                <el-icon><QuestionFilled /></el-icon>
                帮助中心
              </el-dropdown-item>
              <el-dropdown-item divided command="logout">
                <el-icon><SwitchButton /></el-icon>
                退出登录
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </header>
    
    <!-- 主要内容区域 -->
    <main class="main-content">
      <!-- 面包屑导航 -->
      <div v-if="showBreadcrumb" class="breadcrumb-container">
        <el-breadcrumb separator=">" class="page-breadcrumb">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item
            v-for="(item, index) in breadcrumbItems"
            :key="index"
            :to="item.path ? { path: item.path } : null"
          >
            {{ item.title }}
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      
      <!-- 页面内容 -->
      <div class="page-content">
        <router-view v-slot="{ Component, route }">
          <transition name="page-fade" mode="out-in">
            <component :is="Component" :key="route.path" />
          </transition>
        </router-view>
      </div>
    </main>
    
    <!-- 底部 -->
    <footer class="main-footer">
      <div class="footer-content">
        <div class="footer-section">
          <h4>关于我们</h4>
          <ul>
            <li><a href="#">公司介绍</a></li>
            <li><a href="#">联系我们</a></li>
            <li><a href="#">加入我们</a></li>
          </ul>
        </div>
        
        <div class="footer-section">
          <h4>学习支持</h4>
          <ul>
            <li><a href="#">帮助中心</a></li>
            <li><a href="#">学习指南</a></li>
            <li><a href="#">技术支持</a></li>
          </ul>
        </div>
        
        <div class="footer-section">
          <h4>服务条款</h4>
          <ul>
            <li><a href="#">用户协议</a></li>
            <li><a href="#">隐私政策</a></li>
            <li><a href="#">版权声明</a></li>
          </ul>
        </div>
        
        <div class="footer-section">
          <h4>关注我们</h4>
          <div class="social-links">
            <a href="#" class="social-link">
              <el-icon><Platform /></el-icon>
            </a>
            <a href="#" class="social-link">
              <el-icon><ChatDotRound /></el-icon>
            </a>
            <a href="#" class="social-link">
              <el-icon><Message /></el-icon>
            </a>
          </div>
        </div>
      </div>
      
      <div class="footer-bottom">
        <div class="copyright">
          <p>&copy; 2024 在线学习平台. All rights reserved.</p>
        </div>
      </div>
    </footer>
    
    <!-- 回到顶部按钮 -->
    <transition name="fade">
      <el-backtop
        v-show="showBackTop"
        :right="40"
        :bottom="40"
        :visibility-height="300"
      >
        <div class="back-top-btn">
          <el-icon><Top /></el-icon>
        </div>
      </el-backtop>
    </transition>
    
    <!-- 全局加载遮罩 -->
    <div v-if="globalLoading" class="global-loading">
      <el-loading
        :visible="true"
        text="加载中..."
        background="rgba(0, 0, 0, 0.7)"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  House,
  Reading,
  Document,
  ChatDotRound,
  Search,
  Bell,
  Sunny,
  Moon,
  User,
  ArrowDown,
  Setting,
  QuestionFilled,
  SwitchButton,
  Message,
  Platform,
  Top
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { useThemeStore } from '@/stores/theme'
import { getNotifications, markNotificationAsRead, markAllNotificationsAsRead } from '@/api/notification'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const themeStore = useThemeStore()

// 响应式数据
const sidebarCollapsed = ref(false)
const searchKeyword = ref('')
const notifications = ref([])
const showBackTop = ref(false)
const globalLoading = ref(false)

// 计算属性
const activeMenu = computed(() => {
  const path = route.path
  if (path.startsWith('/courses')) return '/courses'
  if (path.startsWith('/exams')) return '/exams'
  if (path.startsWith('/community')) return '/community'
  return path
})

const userInfo = computed(() => userStore.userInfo)
const isDark = computed(() => themeStore.isDark)

const unreadCount = computed(() => {
  return notifications.value.filter(n => !n.read).length
})

const showBreadcrumb = computed(() => {
  // 首页不显示面包屑
  return route.path !== '/'
})

const breadcrumbItems = computed(() => {
  const items = []
  const pathSegments = route.path.split('/').filter(Boolean)
  
  // 根据路径生成面包屑
  let currentPath = ''
  pathSegments.forEach((segment, index) => {
    currentPath += `/${segment}`
    
    // 根据路径段生成标题
    let title = segment
    switch (segment) {
      case 'courses':
        title = '课程中心'
        break
      case 'exams':
        title = '考试中心'
        break
      case 'profile':
        title = '个人中心'
        break
      case 'community':
        title = '学习社区'
        break
      case 'my':
        title = '我的'
        break
      case 'favorite':
        title = '收藏'
        break
      case 'results':
        title = '成绩'
        break
      default:
        // 如果是ID，尝试从路由meta中获取标题
        if (route.meta?.title) {
          title = route.meta.title
        }
    }
    
    items.push({
      title,
      path: index === pathSegments.length - 1 ? null : currentPath
    })
  })
  
  return items
})

// 方法
const goHome = () => {
  router.push('/')
}

const handleMenuSelect = (index) => {
  if (index.startsWith('/')) {
    router.push(index)
  }
}

const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    router.push({
      path: '/search',
      query: { q: searchKeyword.value.trim() }
    })
  }
}

const toggleTheme = () => {
  themeStore.toggleTheme()
}

const handleUserCommand = (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'settings':
      router.push('/profile/settings')
      break
    case 'help':
      router.push('/help')
      break
    case 'logout':
      handleLogout()
      break
  }
}

const handleLogout = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要退出登录吗？',
      '退出登录',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await userStore.logout()
    router.push('/auth/login')
    ElMessage.success('退出登录成功')
  } catch (error) {
    // 用户取消
  }
}

const handleNotificationCommand = (command) => {
  // 处理通知相关命令
}

const handleNotificationClick = async (notification) => {
  try {
    // 标记为已读
    if (!notification.read) {
      await markNotificationAsRead(notification.id)
      notification.read = true
    }
    
    // 根据通知类型跳转
    if (notification.link) {
      router.push(notification.link)
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const markAllAsRead = async () => {
  try {
    await markAllNotificationsAsRead()
    notifications.value.forEach(n => {
      n.read = true
    })
    ElMessage.success('已全部标记为已读')
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const viewAllNotifications = () => {
  router.push('/notifications')
}

const formatTime = (time) => {
  const now = new Date()
  const target = new Date(time)
  const diff = now - target
  
  const minute = 60 * 1000
  const hour = 60 * minute
  const day = 24 * hour
  
  if (diff < minute) {
    return '刚刚'
  } else if (diff < hour) {
    return `${Math.floor(diff / minute)}分钟前`
  } else if (diff < day) {
    return `${Math.floor(diff / hour)}小时前`
  } else if (diff < 7 * day) {
    return `${Math.floor(diff / day)}天前`
  } else {
    return target.toLocaleDateString('zh-CN')
  }
}

// 加载通知
const loadNotifications = async () => {
  try {
    const response = await getNotifications({ limit: 10 })
    notifications.value = response.data
  } catch (error) {
    console.error('加载通知失败:', error)
  }
}

// 监听路由变化
watch(
  () => route.path,
  () => {
    // 路由变化时可以执行一些操作
  }
)

// 监听滚动事件
const handleScroll = () => {
  showBackTop.value = window.scrollY > 300
}

// 生命周期
onMounted(() => {
  loadNotifications()
  
  // 添加滚动监听
  window.addEventListener('scroll', handleScroll)
  
  // 定期刷新通知
  setInterval(loadNotifications, 5 * 60 * 1000) // 5分钟刷新一次
})

// 暴露方法给子组件使用
defineExpose({
  showGlobalLoading: (show = true) => {
    globalLoading.value = show
  }
})
</script>

<style lang="scss" scoped>
.main-layout {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: var(--bg-color);
}

// 顶部导航栏
.main-header {
  background: white;
  border-bottom: 1px solid var(--border-color);
  box-shadow: var(--box-shadow-light);
  position: sticky;
  top: 0;
  z-index: 1000;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 var(--spacing-lg);
}

.header-left {
  display: flex;
  align-items: center;
  gap: var(--spacing-xl);
}

.logo {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  cursor: pointer;
  transition: opacity 0.3s ease;
  
  &:hover {
    opacity: 0.8;
  }
  
  .logo-image {
    height: 36px;
    width: auto;
  }
  
  .logo-text {
    font-size: var(--font-size-large);
    font-weight: 700;
    color: var(--primary-color);
  }
}

.main-nav {
  .nav-menu {
    border: none;
    background: transparent;
    
    :deep(.el-menu-item),
    :deep(.el-sub-menu__title) {
      height: 60px;
      line-height: 60px;
      border-bottom: none;
      
      &:hover {
        background: var(--fill-color-light);
      }
      
      &.is-active {
        background: var(--primary-color-light-9);
        color: var(--primary-color);
      }
    }
    
    :deep(.el-sub-menu) {
      .el-menu-item {
        height: 40px;
        line-height: 40px;
      }
    }
  }
}

.header-right {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
}

.search-box {
  .search-input {
    width: 300px;
    
    :deep(.el-input__wrapper) {
      border-radius: 20px;
    }
  }
}

.notification-btn {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  cursor: pointer;
  transition: background-color 0.3s ease;
  
  &:hover {
    background: var(--fill-color-light);
  }
  
  .el-icon {
    font-size: 20px;
    color: var(--text-color-regular);
  }
}

.theme-toggle {
  width: 40px;
  height: 40px;
  border: none;
  background: transparent;
  
  &:hover {
    background: var(--fill-color-light);
  }
}

.user-menu {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  padding: var(--spacing-sm) var(--spacing-md);
  border-radius: var(--border-radius-base);
  cursor: pointer;
  transition: background-color 0.3s ease;
  
  &:hover {
    background: var(--fill-color-light);
  }
  
  .user-avatar {
    border: 2px solid var(--border-color);
  }
  
  .username {
    font-weight: 500;
    color: var(--text-color-primary);
  }
  
  .dropdown-icon {
    font-size: 12px;
    color: var(--text-color-secondary);
  }
}

// 通知下拉菜单
.notification-dropdown {
  width: 350px;
  max-height: 400px;
  
  .notification-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: var(--spacing-md);
    border-bottom: 1px solid var(--border-color);
    font-weight: 600;
  }
  
  .notification-list {
    max-height: 300px;
    overflow-y: auto;
  }
  
  .notification-item {
    display: flex;
    align-items: flex-start;
    gap: var(--spacing-sm);
    padding: var(--spacing-md);
    border-bottom: 1px solid var(--border-color-lighter);
    cursor: pointer;
    position: relative;
    transition: background-color 0.3s ease;
    
    &:hover {
      background: var(--fill-color-extra-light);
    }
    
    &.unread {
      background: var(--primary-color-light-9);
    }
    
    .notification-icon {
      width: 32px;
      height: 32px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;
      
      &.course {
        background: var(--primary-color-light-9);
        color: var(--primary-color);
      }
      
      &.exam {
        background: var(--warning-color-light-9);
        color: var(--warning-color);
      }
      
      &.system {
        background: var(--info-color-light-9);
        color: var(--info-color);
      }
      
      &.message {
        background: var(--success-color-light-9);
        color: var(--success-color);
      }
    }
    
    .notification-content {
      flex: 1;
      
      .notification-title {
        font-weight: 500;
        color: var(--text-color-primary);
        margin-bottom: var(--spacing-xs);
        @include text-ellipsis;
      }
      
      .notification-desc {
        font-size: var(--font-size-small);
        color: var(--text-color-secondary);
        line-height: 1.4;
        margin-bottom: var(--spacing-xs);
        @include text-ellipsis(2);
      }
      
      .notification-time {
        font-size: var(--font-size-small);
        color: var(--text-color-placeholder);
      }
    }
    
    .unread-dot {
      width: 8px;
      height: 8px;
      border-radius: 50%;
      background: var(--primary-color);
      position: absolute;
      top: var(--spacing-md);
      right: var(--spacing-md);
    }
  }
  
  .notification-footer {
    padding: var(--spacing-md);
    text-align: center;
    border-top: 1px solid var(--border-color);
  }
}

// 主要内容区域
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.breadcrumb-container {
  background: white;
  border-bottom: 1px solid var(--border-color);
  padding: var(--spacing-md) var(--spacing-lg);
  
  .page-breadcrumb {
    :deep(.el-breadcrumb__inner) {
      color: var(--text-color-secondary);
      
      &.is-link {
        color: var(--primary-color);
        
        &:hover {
          color: var(--primary-color-dark);
        }
      }
    }
  }
}

.page-content {
  flex: 1;
  min-height: calc(100vh - 60px - 200px); // 减去header和footer高度
}

// 页面切换动画
.page-fade-enter-active,
.page-fade-leave-active {
  transition: opacity 0.3s ease;
}

.page-fade-enter-from,
.page-fade-leave-to {
  opacity: 0;
}

// 底部
.main-footer {
  background: var(--fill-color-darker);
  color: var(--text-color-secondary);
  margin-top: auto;
}

.footer-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: var(--spacing-xl) var(--spacing-lg);
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: var(--spacing-xl);
}

.footer-section {
  h4 {
    font-size: var(--font-size-medium);
    font-weight: 600;
    color: var(--text-color-primary);
    margin-bottom: var(--spacing-md);
  }
  
  ul {
    list-style: none;
    padding: 0;
    margin: 0;
    
    li {
      margin-bottom: var(--spacing-sm);
      
      a {
        color: var(--text-color-secondary);
        text-decoration: none;
        transition: color 0.3s ease;
        
        &:hover {
          color: var(--primary-color);
        }
      }
    }
  }
  
  .social-links {
    display: flex;
    gap: var(--spacing-md);
    
    .social-link {
      width: 36px;
      height: 36px;
      border-radius: 50%;
      background: var(--fill-color-light);
      display: flex;
      align-items: center;
      justify-content: center;
      color: var(--text-color-secondary);
      transition: all 0.3s ease;
      
      &:hover {
        background: var(--primary-color);
        color: white;
        transform: translateY(-2px);
      }
    }
  }
}

.footer-bottom {
  border-top: 1px solid var(--border-color);
  padding: var(--spacing-lg);
  text-align: center;
  
  .copyright {
    max-width: 1200px;
    margin: 0 auto;
    
    p {
      margin: 0;
      font-size: var(--font-size-small);
      color: var(--text-color-placeholder);
    }
  }
}

// 回到顶部按钮
.back-top-btn {
  width: 40px;
  height: 40px;
  background: var(--primary-color);
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: var(--box-shadow-base);
  transition: all 0.3s ease;
  
  &:hover {
    background: var(--primary-color-dark);
    transform: translateY(-2px);
  }
}

// 全局加载遮罩
.global-loading {
  position: fixed;
  inset: 0;
  z-index: 9999;
}

// 淡入淡出动画
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

// 响应式设计
@include respond-below(lg) {
  .main-header {
    padding: 0 var(--spacing-md);
  }
  
  .header-left {
    gap: var(--spacing-md);
  }
  
  .search-box {
    .search-input {
      width: 250px;
    }
  }
  
  .footer-content {
    grid-template-columns: repeat(2, 1fr);
    padding: var(--spacing-lg) var(--spacing-md);
  }
}

@include respond-below(md) {
  .main-header {
    height: auto;
    flex-direction: column;
    padding: var(--spacing-sm);
    gap: var(--spacing-sm);
  }
  
  .header-left {
    width: 100%;
    justify-content: space-between;
  }
  
  .main-nav {
    display: none; // 在移动端隐藏导航菜单，可以用抽屉菜单替代
  }
  
  .header-right {
    width: 100%;
    justify-content: space-between;
  }
  
  .search-box {
    flex: 1;
    margin-right: var(--spacing-md);
    
    .search-input {
      width: 100%;
    }
  }
  
  .user-menu {
    .username {
      display: none;
    }
  }
  
  .breadcrumb-container {
    padding: var(--spacing-sm) var(--spacing-md);
  }
  
  .footer-content {
    grid-template-columns: 1fr;
    text-align: center;
  }
  
  .notification-dropdown {
    width: 300px;
  }
}

@include respond-below(sm) {
  .logo {
    .logo-text {
      display: none;
    }
  }
  
  .header-right {
    gap: var(--spacing-sm);
  }
  
  .notification-dropdown {
    width: 280px;
  }
}

// 暗色主题适配
@include dark-theme {
  .main-header {
    background: var(--bg-color-dark);
    border-bottom-color: var(--border-color-dark);
  }
  
  .breadcrumb-container {
    background: var(--bg-color-dark);
    border-bottom-color: var(--border-color-dark);
  }
  
  .main-footer {
    background: var(--bg-color-darker);
  }
}
</style>